package com.huatai.manage.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huatai.common.api.R;
import com.huatai.common.config.MinioAPI;
import com.huatai.manage.entity.TbTrialModelEntity;
import com.huatai.manage.service.FileService;
import com.huatai.manage.service.TbTrialModelService;
import com.huatai.manage.vo.ModelFileVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

import static com.huatai.manage.common.constant.ComConstant.MODEL_BUCKET;

/**
 * @ClassName FileServiceImpl
 * @Description TODO 文件业务
 * @Author luoxc
 * @Date 2023/3/14 16:51
 * @Version 1.0
 */
@Service
public class FileServiceImpl implements FileService {

	@Autowired
	private MinioAPI minioAPI;

	@Autowired
	private TbTrialModelService modelManageService;

	/**
	 * 上传文件
	 *
	 * @param file
	 * @return
	 */
	@Override
	public R uploadInputStream(MultipartFile file) {
		String originalFilename = file.getOriginalFilename();
		long count = modelManageService
			.count(Wrappers.<TbTrialModelEntity>lambdaQuery().eq(TbTrialModelEntity::getModelName, originalFilename));
		if (count > 0) return R.fail("文件名重复");
		try {
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
			LocalDate now = LocalDate.now();
			String format = now.format(formatter);
			String fileName = format + "/" + System.currentTimeMillis() + originalFilename;
			minioAPI.uploadInputStream(MODEL_BUCKET, fileName, file.getInputStream(), file.getContentType());
			return R.data(new ModelFileVo(originalFilename, fileName));
		} catch (Exception e) {
			return R.fail("上传失败");
		}
	}

	/**
	 * 下载文件
	 *
	 * @param fileName
	 * @param response
	 * @return
	 */
	@Override
	public void download(String fileName, HttpServletResponse response) {

		try {
			// 获取文件对象
			InputStream object = minioAPI.download(MODEL_BUCKET, fileName);
			byte buf[] = new byte[1024];
			int length = 0;
			response.reset();
			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName.substring(fileName.lastIndexOf("/") + 1), "UTF-8"));
			response.setContentType("application/octet-stream");
			response.setCharacterEncoding("UTF-8");
			OutputStream outputStream = response.getOutputStream();
			// 输出文件
			while ((length = object.read(buf)) > 0) {
				outputStream.write(buf, 0, length);
			}
			// 关闭输出流
			outputStream.close();
		} catch (Exception ex) {
			response.setHeader("Content-type", "text/html;charset=UTF-8");
			String data = "文件下载失败";
			OutputStream ps = null;
			try {
				ps = response.getOutputStream();
				ps.write(data.getBytes("UTF-8"));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		/*try {
			InputStream download = minioAPI.download(MODEL_BUCKET, objectKey);
			byte buf[] = new byte[1024];
			int length = 0;
			response.reset();
			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(objectKey.substring(objectKey.lastIndexOf("/") + 1), "UTF-8"));
			response.setContentType("application/octet-stream");
			response.setCharacterEncoding("UTF-8");
			OutputStream outputStream = response.getOutputStream();
			// 输出文件
			while ((length = download.read(buf)) > 0) {
				outputStream.write(buf, 0, length);
			}
			// 关闭输出流
			outputStream.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}*/

		/*InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			if (StringUtils.isBlank(objectKey)) {
				response.setHeader("Content-type", "text/html;charset=UTF-8");
				String data = "文件下载失败";
				OutputStream ps = response.getOutputStream();
				ps.write(data.getBytes("UTF-8"));
				return false;
			}

			outputStream = response.getOutputStream();
			// 获取文件对象
			inputStream = minioAPI.download(MODEL_BUCKET, objectKey);
			byte buf[] = new byte[1024];
			int length = 0;
			response.reset();
			response.setHeader("Content-Disposition", "attachment;objectKey=" +
				URLEncoder.encode(objectKey.substring(objectKey.lastIndexOf("/") + 1), "UTF-8"));
			response.setContentType("application/octet-stream");
			response.setCharacterEncoding("UTF-8");
			// 输出文件
			while ((length = inputStream.read(buf)) > 0) {
				outputStream.write(buf, 0, length);
			}
			inputStream.close();
			return true;
		} catch (Throwable ex) {
			response.setHeader("Content-type", "text/html;charset=UTF-8");
			String data = "文件下载失败";
			try {
				OutputStream ps = response.getOutputStream();
				ps.write(data.getBytes("UTF-8"));
			} catch (IOException e) {
				e.printStackTrace();
			}
			return false;
		} finally {
			try {
				outputStream.close();
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}*/
	}
}
